<template>
	<div class="system-role-container">
		<el-dialog
			title="编辑角色"
			destroy-on-close
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			v-model="isShowDialog"
			:show-close="false"
			width="369px"
		>
			<el-form :model="ruleForm" :rules="rules" ref="form" size="small" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色名称" prop="roleName">
							<el-input v-model="ruleForm.roleName" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="权限树" prop="permissions">
							<el-input clearable v-model="filterText" placeholder="请输入关键字" />
							<el-tree
								style="margin-top:15px"
								ref="treeMenuEdit"
								node-key="Permission"
								:filter-node-method="filterNode"
								:props="props"
								:data="treeList"
								show-checkbox
								check-strictly
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="small">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="small">提 交</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, watch, ref, nextTick, defineComponent } from 'vue';
import { ElMessageBox } from 'element-plus';
import { getMenuTree } from '/@/api/platform/menu/index'
import { edit } from '/@/api/platform/role/index'
import { getUserInfo } from '/@/api/platform/login/index'
import { Session } from '/@/utils/storage';
import { store } from '/@/store';
import { setBackEndControlRefreshRoutes } from '/@/router/backEnd';
export default defineComponent({
	name: 'EditRole',
	setup(props: any, context: any) {
		const state = reactive({
			isShowDialog: false,
			ruleForm: {
				id: 0,
				roleName: "", // 角色名称
				permissions: [{}], // 角色权限树
			},
			rules: {
				roleName: [{
					required: true,
					message: "请输入角色名称！",
					trigger: "blur"
				}],
				permissions: [{
					required: true,
					validator: (rule: any, value: any, callback: any) => {
						//获取全选节点
						const checkMenu = treeMenuEdit.value.getCheckedNodes();
						//获取半选节点
						const halfCheckMenu = treeMenuEdit.value.getHalfCheckedNodes()
						state.ruleForm.permissions = [];
						if (checkMenu && checkMenu.length > 0) {
							checkMenu.forEach((menu: any) => {
								state.ruleForm.permissions.push(
									{
										"permissionName": menu.MenuName,
										"permission": menu.Permission
									})
							});
							if (halfCheckMenu && halfCheckMenu.length > 0) {
								halfCheckMenu.forEach((menu: any) => {
									state.ruleForm.permissions.push({
										"permissionName": menu.MenuName,
										"permission": menu.Permission
									})
								});
							}
							callback()
						} else {
							callback(new Error('请选择角色授予的权限！'))
						}
					},
					trigger: "blur"
				}]
			},
			props: {
				label: 'MenuName',
				children: 'Children',
			},
			treeList: [],
			filterText: ""
		});
		const userID = store.state.userInfos.userInfos.id;
		const treeMenuEdit = ref();
		const form = ref();
		watch(() => state.filterText, (value) => {
			treeMenuEdit.value.filter(value);
		})
		const filterNode = (value: any, data: any) => {
			if (!value) return true
			return data.MenuName.indexOf(value) !== -1
		}
		const initTableData = () => {
			getMenuTree({ parentID: 0 }).then((res) => {
				state.treeList = res.Extras;
			})
		};
		initTableData();
		// 打开弹窗
		const openDialog = (row?: object) => {
			state.ruleForm.id = row.id;
			state.ruleForm.roleName = row.roleName;
			state.isShowDialog = true;
			nextTick(() => {
				let data: any = [];
				console.log(row);
				row?.permissions.forEach((item: any) => {
					data.push({ "Permission": item.permission });
				});
				treeMenuEdit.value.setCheckedNodes(data);
			})
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
		};
		// 取消
		const onCancel = () => {
			closeDialog();
			initForm();
		};
		// 新增
		const onSubmit = () => {
			form.value.validate((valid: boolean) => {
				if (!valid) {
					return false;
				}
				//获取全选节点
				const checkMenu = treeMenuEdit.value.getCheckedNodes();
				//获取半选节点
				const halfCheckMenu = treeMenuEdit.value.getHalfCheckedNodes()
				if (!state.ruleForm.roleName) {
					ElMessageBox.alert("请输入角色名称！");
					return;
				}
				state.ruleForm.permissions = [];
				if (checkMenu && checkMenu.length > 0) {
					checkMenu.forEach((menu: any) => {
						state.ruleForm.permissions.push(
							{
								"roleId": state.ruleForm.id,
								"permissionName": menu.MenuName,
								"permission": menu.Permission
							})
					});
					if (halfCheckMenu && halfCheckMenu.length > 0) {
						halfCheckMenu.forEach((menu: any) => {
							state.ruleForm.permissions.push(
								{
									"roleId": state.ruleForm.id,
									"permissionName": menu.MenuName,
									"permission": menu.Permission
								})
						});
					}
				}
				else {
					ElMessageBox.alert("请选择角色授予的权限！");
					return;
				}
				edit(state.ruleForm).then((res) => {
					getUserInfo({ id: userID }).then((userinfo) => {
						const userInfos = {
							account: userinfo.Extras.Account,
							nickname: userinfo.Extras.NickName,
							avatar: userinfo.Extras.Avatar,
							authPageList: userinfo.Extras.Permissions,
							id: userinfo.Extras.Id
						};
						// 存储用户信息到浏览器缓存
						Session.set('userInfo', userInfos);
						// 存储用户信息到vuex
						store.dispatch('userInfos/setUserInfos', userInfos);
						setBackEndControlRefreshRoutes() // 刷新菜单
						ElMessageBox.alert(res.Message, '提示', {}).then(() => {
							// 刷新父级数据
							context.emit("sendRefresh");
							//修改角色权限后需要刷新userinfo的权限缓存

							closeDialog(); // 关闭弹窗
							initForm();
						}).catch(() => { });
					})
				})
			})
		};
		const initForm = () => {
			form.value.resetFields();
		};
		return {
			openDialog,
			closeDialog,
			onCancel,
			onSubmit,
			...toRefs(state),
			treeMenuEdit,
			form,
			filterNode
		};
	},
});
</script>